<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="60px">

            <el-form-item label="网关" prop="gatewayId">
                <gateway-select @changeGateway="changeGateway"/>
            </el-form-item>

            <el-form-item label="名称" prop="loopName">
                <el-input
                    size="small"
                    v-model="queryParams.loopName"
                    placeholder="请输入控制点名称"
                    clearable
                />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="handleQuery">刷新</el-button>
            </el-form-item>

        </el-form>

        <div v-if="loopList.length === 0" v-loading="globalLoading">
            <el-empty description="暂无控制点"></el-empty>
        </div>

        <el-row :gutter="20" v-if="loopList.length > 0" v-loading="globalLoading">

            <el-col :xs="24" :sm="8" :md="6" :lg="6" :xl="4" style="margin-top: 20px"
                    v-for="(item, index) in this.loopList" :key="index"
            >

                <el-card class="box-card" v-loading="item.loading">

                    <div slot="header" class="clearfix"
                         style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
                    >
            <span style="font-size: 16px; height: 35px; display: inline-block; line-height: 35px">{{
                    item.loopName
                }}</span>


                        <el-link :underline="false" style="float: right; height: 35px; line-height: 35px"
                                 v-if="item.loopType === '0'" type="info"
                        >开关型
                        </el-link>
                        <el-link :underline="false" style="float: right; height: 35px; line-height: 35px"
                                 v-if="item.loopType === '1'" type="info"
                        >数值型
                        </el-link>
                        <!--            <el-tag style="float: right; " v-if="item.loopValue !== '1'" type="danger">关</el-tag>-->
                        <!--            <el-tag style="float: right; " v-if="item.loopValue === '1'" type="success">开</el-tag>-->
                        <!--            <el-button style="float: right; padding: 3px 0" type="text" @click="readModule(index)">读取</el-button>-->
                    </div>


                    <el-form>

                        <el-form-item label="设备状态">
                            <svg-icon v-if="item.serverOnline === '1'" icon-class="wifi-online"
                                      style="width: 3em; height: 3em;"
                            />
                            <svg-icon v-if="item.serverOnline === '0'||item.serverOnline===null"
                                      icon-class="wifi-offline"
                                      style="width: 3em; height: 3em;"
                            />
                        </el-form-item>

                        <!--                                    <el-form-item label="开关状态">-->
                        <!--                                      <el-tag v-if="item.loopValue !== '1'" type="danger">关</el-tag>-->
                        <!--                                      <el-tag v-if="item.loopValue === '1'" type="success">开</el-tag>-->
                        <!--                        &lt;!&ndash;              <el-tag v-if="item.loopValue === '2'" type="warning">未知</el-tag>&ndash;&gt;-->
                        <!--                                    </el-form-item>-->

                        <el-form-item label="操作">

                            <!--              <el-button v-if="item.loopValue !== '1'" type="success" @click="handleLoopStatusChange(index, '1')">开启</el-button>-->
                            <!--              <el-button v-if="item.loopValue === '1'" type="danger" @click="handleLoopStatusChange(index, '0')">关闭</el-button>-->

                            <el-switch v-if="item.loopType==='0'"
                                       v-model="item.switchValue"
                                       :width="100"
                                       active-color="#13ce66"
                                       active-value="1"
                                       inactive-value="0"
                                       active-text="开启"
                                       inactive-text="关闭"
                                       @change="handleLoopStatusChange(index, item.switchValue)"
                            >
                            </el-switch>

                            <div v-if="item.loopType==='1'" style="display: flex">
                                <el-input clearable v-model="item.loopValue" placeholder="输入数值"></el-input>
                                <el-button style="margin-left: 5px"
                                           type="success"
                                           size="small" @click="handleLoopSetLoopValue(index, item.loopValue)"
                                >设置
                                </el-button>
                            </div>

                        </el-form-item>

                    </el-form>
                </el-card>
            </el-col>

        </el-row>

    </div>
</template>

<script>
import { sendMessage } from '@/api/netty/nettyMessage'
import { listLoop } from '@/api/equipment/loop'
import gatewaySelect from '../../common/GatewaySelect.vue'

const common = require('@/api/common/common')

export default {
    inject: ['reload'],
    name: 'controlLoop',
    components: {
        gatewaySelect
    },
    data() {
        return {
            queryParams: {
                gatewayId: 0,
                gatewayNumber: null
                // pageNum: 1,
                // pageSize: 10,
            },
            // loopValue: true,
            showSearch: true,

            gatewayList: [],

            loopList: [],

            globalLoading: false,
            gatewayListOption: [],

            total: 0,

            webClientId: this.genUUID(10, 16),
            messageObj: {
                instruction: '0'
            },
            form: {},
            // 获取当前索引
            currentIndex: null
        }
    },
    created() {
    },
    destroyed() {
        if (this.ws !== undefined) {
            this.ws.close()
        }
    },
    methods: {
        handleQuery() {
            this.getList()
        },
        // 接收子组件传递的消息
        changeGateway(obj) {
            this.gatewayListOption = obj.gatewayListOption
            this.queryParams.gatewayId = obj.gatewayId
            console.log('666', obj.gatewayId)
            this.getList()
        },
        getList() {

            this.globalLoading = true

            listLoop(this.queryParams).then(response => {

                this.loopList = []

                response.data.forEach(item => {
                    item.switchValue = item.loopValue
                    item.loading = false

                    this.loopList.push(item)
                })

                this.globalLoading = false

                // console.log(this.loopList)
            }, error => {
                this.globalLoading = false
            })
        },
        // loopValue 改变后的值
        handleLoopStatusChange(index, loopValue) {
            this.currentIndex = index
            if (loopValue === '0') {
                this.closeLoop(index, '0')
            }
            if (loopValue === '1') {
                this.openLoop(index, '1')
            }
        },
        closeLoop(index, switchValue) {
            this.loopList[index].loading = true
            this.form = this.loopList[index]
            let beforeValue = this.form.loopValue
            let data = {
                'key': 'closeLoop',
                'index': index,
                'before': beforeValue,
                'after': switchValue
            }
            this.messageObj.gatewayNumber = this.form.gatewayNumber
            this.messageObj.loopId = this.form.loopId
            this.messageObj.paramType = '0'
            this.messageObj.operationType = '1'
            this.messageObj.writeValue = '0'
            this.messageObj.data = data
            this.messageObj.webClientId = this.webClientId
            this.send2Web(index, beforeValue)
        },
        openLoop(index, switchValue) {
            this.loopList[index].loading = true
            this.form = this.loopList[index]
            let beforeValue = this.form.loopValue
            let data = {
                'key': 'openLoop',
                'index': index,
                'before': beforeValue,
                'after': switchValue
            }
            this.messageObj.gatewayNumber = this.form.gatewayNumber
            this.messageObj.loopId = this.form.loopId
            this.messageObj.paramType = '0'
            this.messageObj.operationType = '1'
            this.messageObj.writeValue = '1'
            this.messageObj.data = data
            this.messageObj.webClientId = this.webClientId
            this.send2Web(index, beforeValue)
        },
        handleLoopSetLoopValue(index, value) {
            this.loopList[index].loading = true
            this.form = this.loopList[index]

            let beforeValue = this.form.loopValue

            let data = {
                'key': 'setLoop',
                'index': index,
                'before': beforeValue,
                'after': value
            }

            this.messageObj.gatewayNumber = this.form.gatewayNumber
            this.messageObj.loopId = this.form.loopId
            this.messageObj.paramType = '0'
            this.messageObj.operationType = '1'
            this.messageObj.writeValue = value
            this.messageObj.data = data
            this.messageObj.webClientId = this.webClientId
            this.send2Web(index, beforeValue)
        },
        send2Web(index, beforeValue) {
            sendMessage(this.messageObj).then(response => {
                if (response.code === 200) {
                    // 成功后建立websocket
                    let obj = {
                        'webClientId': this.webClientId,
                        'type': 'login'
                    }
                    this.sendMessage(obj)
                }
            }, error => {
                this.loopList[index].loading = false
                this.loopList[index].loopValue = beforeValue
                this.loopList[index].switchValue = beforeValue
            })
        },
        // websocket 发送消息给服务器
        sendMessage(obj) {
            // this.$websocket.sendMsg(JSON.stringify(obj))
            // this.$websocket.sendMsg(obj)
            if (this.ws !== undefined && this.ws.readyState === 1) {
                console.log('已存在')
                // this.$websocket.sendMsg(obj)
            } else {
                this.localSocket(obj)
            }
        },
        localSocket(obj) {
            let that = this
            if ('WebSocket' in window) {
                console.log('您的浏览器支持 WebSocket')
                // console.log('that.ws', that.ws)
                if (that.ws !== undefined && that.ws.readyState === 1) {
                    console.log('存在连接')
                    return
                }
                that.ws = new WebSocket(that.$websocket.url)
                that.$websocket.setWs(that.ws)
                that.ws.onopen = function() {
                    console.log('开始连接')
                    // that.sendMessage(obj)
                    that.$websocket.sendMsg(obj)
                }
                // websocket 接收服务器消息
                that.ws.onmessage = function(result) {
                    console.log('收到websocket回复', result)
                    // console.log('回复data', result.data)
                    that.processData(result.data)
                }
                that.ws.onclose = function() {
                    // 防链接超时，（websocket在一定时间内没有数据交互，就会断开），关闭后重启
                    console.log('连接已关闭')
                    that.ws.close()
                    // setTimeout(() => {
                    //     that.localSocket()
                    // }, 2000)
                }
            } else {
                // 浏览器不支持 WebSocket
                console.log('您的浏览器不支持 WebSocket!')
            }
        },
        processData(json) {
            console.log('json', json)
            let data = {}
            try {
                data = JSON.parse(json)
                if (this.loopList[this.currentIndex].deviceType === 0) {
                    let data2 = JSON.parse(data.data)
                    if (data2.code === 200) {
                        if (data2.data.type === 1) {
                            if (data2.data.switchStatus === '0') {
                                this.$message.success('开启成功')
                            } else {
                                this.$message.success('关闭成功')
                            }
                            this.loopList[this.currentIndex].loading = false
                        }
                    }
                }
            } catch (e) {
            }
            // console.log('data', data)
            let webClientId = data['webClientId']
            let cause = data['cause']
            if (webClientId === undefined) {
                return
            }
            // console.log('回复的webClientId', webClientId)
            let text = null
            let key = data['key']
            let index = data['index']
            let beforeValue = data['before']
            this.loopList[index].loading = false
            if ('openLoop' === key) {
                text = '开启成功'
            }
            if ('closeLoop' === key) {
                text = '关闭成功'
            }
            if ('setLoop' === key) {
                text = '设置成功'
            }
            // let id = data['id']
            let value = data['value']
            let status = data['status']
            let paramType = data['paramType']
            if (webClientId === this.webClientId) {
                // console.log('id', id)
                if (cause !== undefined) {
                    this.$message.error(cause)
                    this.loopList[index].loopValue = beforeValue
                    this.loopList[index].switchValue = beforeValue
                    return
                }
                if (value !== undefined) {
                    if (paramType === '0') {
                        this.form.loopValue = value
                    }
                    if (paramType === '1') {
                        this.form.loopWorkType = value
                    }
                }
                if (status !== undefined) {
                    this.form.status = status
                }
                this.$message.success(text)
            }
        }
    }
}
</script>

<style scoped>
.el-switch__core {
    height: 50px;
}
</style>
